package cn.sangkf.litemall.product.service.impl;

import cn.sangkf.litemall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sangkf.litemall.common.utils.PageUtils;
import cn.sangkf.litemall.common.utils.Query;

import cn.sangkf.litemall.product.dao.CategoryDao;
import cn.sangkf.litemall.product.entity.CategoryEntity;
import cn.sangkf.litemall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        this.baseMapper.deleteBatchIds(asList);
    }

    /**
     * 级联更新
     * @param category
     */
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0L) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 以树形结构返回所有分类
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 获取所有分类
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(null);
        // 获取一级分类
        List<CategoryEntity> parentCategories = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrenCategories(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((category1, category2) -> (category1.getSort() == null ? 0 : category1.getSort())
                        - (category2.getSort() == null ? 0 : category2.getSort())
                ).collect(Collectors.toList());
        return parentCategories;
    }

    /**
     * 根据父分类获取子分类
     *
     * @param root
     * @param categoryEntities
     * @return
     */
    private List<CategoryEntity> getChildrenCategories(CategoryEntity root, List<CategoryEntity> categoryEntities) {
        return categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildrenCategories(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((category1, category2) -> (category1.getSort() == null ? 0 : category1.getSort())
                        - (category2.getSort() == null ? 0 : category2.getSort())
                ).collect(Collectors.toList());
    }
}